﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Serialization;

namespace BestWise.Common
{
    public static class StringExtensions
    {
        private static Regex regexDiv = new Regex("^<div(\\s+[^>]+)*?>", RegexOptions.IgnoreCase);
        private static IDictionary<string, string> contentTypeFileExtensions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        private const string patternSpace = "((^((\\s)|(&nbsp;)){1,})|(((\\s)|(&nbsp;)){1,}$))";
        private const string patternClearHtmlAttribute = "\\<\\w+?\\s+?([^\\>]*?\\s+?)*?(?<clear>\\=[\"']{0,2})(\\s+?[^\\>]*?)*?\\>";
        private const string optionPattern = "^[a-zA-Z0-9])．\\S+$";
        private static Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
        private static readonly char[] _word =
        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
          'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
          'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
          'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
          'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
          'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
          'Y', 'Z' };

        /// <summary>
        /// 数字字符串的正则表达式
        /// </summary>
        public const string REGEX_NUMBERIC = "^[0-9]+$";
        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsNumeric(this string helper)
        {
            return new Regex(REGEX_NUMBERIC).IsMatch(helper);
        }

        /// <summary>
        /// 数字字符串 可带正负号的正则表达式
        /// </summary>
        public const string REGEX_NUMBERICOFSIGN = "^[+-]?[0-9]+$";
        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsNumericOfSign(this string helper)
        {
            return new Regex(REGEX_NUMBERICOFSIGN).IsMatch(helper);
        }

        /// <summary>
        /// 浮点数字符串的正则表达式
        /// </summary>
        public const string REGEX_DECIMAL = "^[0-9]+([.]?[0-9]+)?$";
        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsDecimal(this string helper)
        {
            return new Regex(REGEX_DECIMAL).IsMatch(helper);
        }

        /// <summary>
        /// 浮点数字符串的正则表达式
        /// </summary>
        public const string REGEX_DECIMALOFSIGN = "^[+-]?[0-9]+([.]?[0-9]+)?$";
        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsDecimalOfSign(this string helper)
        {
            return new Regex(REGEX_DECIMALOFSIGN).IsMatch(helper);
        }

        /// <summary>
        /// 大写字母字符串的正则表达式
        /// </summary>
        public const string REGEX_UPPERCASE = "^[A-Z]+$";
        /// <summary>
        /// 是否是大写字母字符
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsUppercase(this string helper)
        {
            return new Regex(REGEX_UPPERCASE, RegexOptions.Compiled).IsMatch(helper);
        }

        /// <summary>
        /// 小写字母字符串的正则表达式
        /// </summary>
        public const string REGEX_LOWERCASE = "^[a-z]+$";
        /// <summary>
        /// 是否是小写字母字符
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsLowercase(this string helper)
        {
            return new Regex(REGEX_LOWERCASE, RegexOptions.Compiled).IsMatch(helper);
        }

        /// <summary>
        /// 包含中文字符的正则表达式
        /// </summary>
        public const string REGEX_HASCHINESE = "[\u4e00-\u9fa5]";
        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsHasChinese(this string helper)
        {
            return new Regex(REGEX_HASCHINESE).IsMatch(helper);
        }

        /// <summary>
        /// 邮件地址的正则表达式
        /// </summary>
        public const string REGEX_EMAIL = "^[-\\w\\.]+@([-\\w]+\\.)+[a-z]{2,3}$";
        /// <summary>
        /// 是否是邮件地址
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsEmail(this string helper)
        {
            return new Regex(REGEX_EMAIL, RegexOptions.IgnoreCase).IsMatch(helper);
        }

        /// <summary>
        /// URL的正则表达式
        /// </summary>
        public const string REGEX_URL = "^([a-zA-Z]{3,5}:\\/\\/)?[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?$";
        /// <summary>
        /// 是否是正确的URL
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsURL(this string helper)
        {
            return new Regex(REGEX_URL, RegexOptions.IgnoreCase).IsMatch(helper);
        }

        /// <summary>
        /// 电话号码的正则表达式
        /// </summary>
        public const string REGEX_PHONE = "^[0-9]+[-]?[0-9]+[-]?[0-9]$";
        /// <summary>
        /// 是否是电话号码
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsPhone(this string helper)
        {
            return new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$").IsMatch(helper);
        }

        /// <summary>
        /// 是否是GUID
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsGuid(this string helper)
        {
            return new Regex("^[A-Za-z0-9]{8}(-[A-Za-z0-9]{4}){3}-[A-Za-z0-9]{12}$").IsMatch(helper);
        }

        /// <summary>
        /// base64字符串的正则表达式
        /// </summary>
        public const string REGEX_BASE64STRING = @"[A-Za-z0-9\+\/\=]";
        /// <summary>
        /// 判断是否为base64字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <returns>判断结果</returns>
        public static bool IsBase64String(this string helper)
        {
            return Regex.IsMatch(helper, REGEX_BASE64STRING);
        }

        /// <summary>
        /// 有Sql危险字符的正则表达式
        /// </summary>
        public const string REGEX_SAFESQLSTRING = @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']";
        /// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="helper"></param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(this string helper)
        {
            return !Regex.IsMatch(helper, REGEX_SAFESQLSTRING);
        }

        /// <summary>
        /// 有危险的可能用于链接的字符串的正则表达式
        /// </summary>
        public const string REGEX_SAFEUSERINFOSTRING = @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest";
        /// <summary>
        /// 检测是否有危险的可能用于链接的字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <returns>判断结果</returns>
        public static bool IsSafeUserInfoString(this string helper)
        {
            return !Regex.IsMatch(helper, REGEX_SAFEUSERINFOSTRING);
        }
        /// <summary>
        /// ip地址的正则表达式
        /// </summary>
        public const string REGEX_IPADDRESS = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
        /// <summary>
        /// 检测是否为ip
        /// </summary>
        /// <param name="helper"></param>
        /// <returns>判断结果</returns>
        public static bool IsIPAddress(this string helper)
        {
            return Regex.IsMatch(helper, REGEX_IPADDRESS);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsIPSect(this string helper)
        {
            return Regex.IsMatch(helper, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static bool IsMapPath(this string helper)
        {
            return Regex.IsMatch(helper, "^((\\\\\\\\)|(\\w:\\\\))", RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="separator">分离字符</param>
        /// <returns>一个数组</returns>
        public static string[] Split(this string helper, string separator)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                if (helper.IndexOf(separator) < 0)
                    return new string[] { helper };

                return Regex.Split(helper, Regex.Escape(separator), RegexOptions.IgnoreCase);
            }
            else
                return new string[0] { };
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="separator">分离字符</param>
        /// <param name="count">要返回的子字符串的最大数量。</param>
        /// <returns>一个数组</returns>
        public static string[] Split(this string helper, string separator, int count)
        {
            string[] result = new string[count];
            string[] splited = helper.Split(separator);
            for (int i = 0; i < count; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }

            return result;
        }

        /// <summary>
        /// 获取当前字符串的IP或域名部分
        /// </summary>
        /// <param name="helper"></param>
        /// <returns>IP或域名</returns>
        public static string GetIPOrDomainByPath(this string helper)
        {
            string returnValue = string.Empty;
            Regex rgx = new Regex(@"\\(?<Domain>(([^\\]+?)|((\d{1,3}\.){3}\d{1,3})))\\w*", RegexOptions.IgnoreCase);
            if (rgx.IsMatch(helper))
                returnValue = rgx.Match(helper).Groups["Domain"].Value.Trim();
            return returnValue;
        }

        /// <summary>
        /// 将字符串截取为指定长度的字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string Left(this string helper, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                if (helper.Length > length)//按最大长度截取字符串
                    helper = helper.Substring(0, length);
            }
            return helper;
        }

        /// <summary>
        /// 将字符串从右截取为指定长度的字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string Right(this string helper, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                if (helper.Length > length)//按最大长度截取字符串
                    helper = helper.Substring(helper.Length - length);
            }
            return helper;
        }

        /// <summary>
        /// 将字符串从中间截取为指定长度的字符串
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string Middle(this string helper, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                if (helper.Length > length)//按最大长度截取字符串
                    helper = helper.Left(length / 2) + "..." + helper.Right(length / 2);
            }
            return helper;
        }

        /// <summary>
        /// 将字符串截取为指定长度的字符串(清除HTML标记)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string LeftByHtml(this string helper, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
                return helper.ClearHtml().Left(length);
            return string.Empty;
        }
        /// <summary>
        ///  将字符串截取为指定长度的字符串(清除HTML标记 + ...)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string LeftByHtmls(this string helper, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                if (helper.Length > length)//按最大长度截取字符串
                    helper = helper.Left(length) + "...";
            }
            return helper;
        }
        /// <summary>
        /// 将字符串从中间截取为指定长度的字符串(清除HTML标记)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string MiddleByHtml(this string helper, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
                return helper.ClearHtml().Middle(length);
            return string.Empty;
        }

        /// <summary>
        /// 将字符串从右截取为指定长度的字符串(清除HTML标记)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RightByHtml(this string helper, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
                return helper.ClearHtml().Right(length);
            return string.Empty;
        }

        /// <summary>
        /// 将字符串截取为指定长度的字符串(区分双字节字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <param name="hasEllipsis">是否有省略号(默认：无)</param>
        /// <returns></returns>
        public static string LeftOfDoublet(this string helper, int length, bool hasEllipsis)
        {
            return helper.LeftOfSpecial("[^\x00-\xff]", length, hasEllipsis);
        }

        /// <summary>
        /// 将字符串截取为指定长度的字符串(区分双字节字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string LeftOfDoublet(this string helper, int length)
        {
            return helper.LeftOfDoublet(length, false);
        }

        /// <summary>
        /// 将字符串从中间截取为指定长度的字符串(区分双字节字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string MiddleOfDoublet(this string helper, int length)
        {
            return helper.MiddleOfSpecial("[^\x00-\xff]", length);
        }

        /// <summary>
        /// 将字符串从右截取为指定长度的字符串(区分双字节字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <param name="hasEllipsis">是否有省略号(默认：无)</param>
        /// <returns></returns>
        public static string RightOfDoublet(this string helper, int length, bool hasEllipsis)
        {
            return helper.RightOfSpecial("[^\x00-\xff]", length, hasEllipsis);
        }

        /// <summary>
        /// 将字符串从右截取为指定长度的字符串(区分双字节字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RightOfDoublet(this string helper, int length)
        {
            return helper.RightOfDoublet(length, false);
        }

        /// <summary>
        /// 将字符串截取为指定长度的字符串(区分中文字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <param name="hasEllipsis">是否有省略号(默认：无)</param>
        /// <returns></returns>
        public static string LeftOfChinese(this string helper, int length, bool hasEllipsis)
        {
            return helper.LeftOfSpecial("[\u4e00-\u9fa5]", length, hasEllipsis);
        }

        /// <summary>
        /// 将字符串截取为指定长度的字符串(区分中文字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string LeftOfChinese(this string helper, int length)
        {
            return helper.LeftOfChinese(length, false);
        }

        /// <summary>
        /// 将字符串从中间截取为指定长度的字符串(区分中文字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string MiddleOfChinese(this string helper, int length)
        {
            return helper.MiddleOfSpecial("[\u4e00-\u9fa5]", length);
        }

        /// <summary>
        /// 将字符串从右截取为指定长度的字符串(区分中文字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <param name="hasEllipsis">是否有省略号(默认：无)</param>
        /// <returns></returns>
        public static string RightOfChinese(this string helper, int length, bool hasEllipsis)
        {
            return helper.RightOfSpecial("[\u4e00-\u9fa5]", length, hasEllipsis);
        }

        /// <summary>
        /// 将字符串从右截取为指定长度的字符串(区分中文字符)
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RightOfChinese(this string helper, int length)
        {
            return helper.RightOfChinese(length, false);
        }


        /// <summary>
        /// 字符串编码
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static string HtmlEncode(this string helper)
        {
            return HttpUtility.HtmlEncode(helper);
        }

        /// <summary>
        /// 清除HTML标记
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static string ClearHtml(this string helper)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                //删除脚本
                helper = Regex.Replace(helper, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
                //删除HTML
                helper = Regex.Replace(helper, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"<!--.*?-->", "", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"-->", "", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"<!--.*", "", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(middot);", "·", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(rdquo);", "”", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(ldquo);", "“", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(times);", "×", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(rsquo);", "’", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(hellip);", "…", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(deg);", "°", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
                helper = Regex.Replace(helper, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            }
            return helper.HtmlEncode();
        }


        /// <summary>
        /// 字符串清理
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string HtmlToText(this string helper, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();

            // 检查是否为空
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim().Left(maxLength);
                //替换危险字符
                for (int i = 0; i < helper.Length; i++)
                {
                    switch (helper[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(helper[i]);
                            break;
                    }
                }
                retVal.Replace("'", " ");// 替换单引号
            }
            return retVal.ToString();
        }


        /// <summary>
        /// 转换成 HTML code
        /// </summary>
        /// <param name="helper">string</param>
        /// <returns>string</returns>
        public static string Encode(this string helper)
        {
            helper = helper.Replace("&", "&amp;");
            helper = helper.Replace("'", "''");
            helper = helper.Replace("\"", "&quot;");
            helper = helper.Replace("　", "&nbsp;");
            helper = helper.Replace(" ", "&nbsp;");
            helper = helper.Replace("<", "&lt;");
            helper = helper.Replace(">", "&gt;");
            helper = helper.Replace("\n", "<br>");
            return helper;
        }


        /// <summary>
        ///解析html成 普通文本
        /// </summary>
        /// <param name="helper">string</param>
        /// <returns>string</returns>
        public static string Decode(this string helper)
        {
            helper = helper.Replace("<br>", "\n");
            helper = helper.Replace("&gt;", ">");
            helper = helper.Replace("&lt;", "<");
            helper = helper.Replace("&nbsp;", " ");
            helper = helper.Replace("&quot;", "\"");
            return helper;
        }

        public static string TextClear(this string helper)
        {
            if (helper == null)
            {
                return null;
            }
            if (helper == "")
            {
                return "";
            }
            helper = helper.Replace(",", "");//去除,
            helper = helper.Replace("<", "");//去除<
            helper = helper.Replace(">", "");//去除>
            helper = helper.Replace("--", "");//去除--
            helper = helper.Replace("'", "");//去除'
            helper = helper.Replace("\"", "");//去除"
            helper = helper.Replace("=", "");//去除=
            helper = helper.Replace("%", "");//去除%
            helper = helper.Replace(" ", "");//去除空格
            return helper;
        }

        #region 是否由特定字符组成
        public static bool isContainSameChar(this string helper)
        {
            string charInput = string.Empty;
            if (!string.IsNullOrWhiteSpace(helper))
                charInput = helper.Left(1);
            return helper.isContainSameChar(charInput, helper.Length);
        }

        public static bool isContainSameChar(this string helper, string charInput, int lenInput)
        {
            if (string.IsNullOrWhiteSpace(charInput))
                return false;
            else
            {
                Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput));
                //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
                Match m = RegNumber.Match(helper);
                return m.Success;
            }
        }
        #endregion

        /// <summary>
        /// 获取当前字符串符合正则表达式，且指定组名的名称的字符串值。
        /// </summary>
        /// <param name="helper">当前字符串。</param>
        /// <param name="pattern">要匹配的正则表达式模式。</param>
        /// <param name="groupname">捕获组的名称（默认为:value）。</param>
        /// <returns>返回捕获组的名称的字符串值。</returns>
        public static string GetStringValueByRegex(this string helper, string pattern, string groupname)
        {
            if (string.IsNullOrWhiteSpace(groupname)) groupname = "value";
            string result = string.Empty;
            Match m = Regex.Match(helper, pattern, RegexOptions.IgnoreCase);
            if (m.Success)
                result = m.Groups[groupname].Value.Trim();
            return result;
        }

        /// <summary>
        /// 获取当前字符串符合正则表达式，且 value 组的名称的字符串值。
        /// </summary>
        /// <param name="helper">当前字符串。</param>
        /// <param name="pattern">要匹配的正则表达式模式。</param>
        /// <returns>返回捕获 value 组的名称为 value 的字符串值。</returns>
        public static string GetStringValueByRegex(this string helper, string pattern)
        {
            return helper.GetStringValueByRegex(pattern, string.Empty);
        }

        /// <summary>
        /// 获取当前字符串符合正则表达式，且指定组的名称的整型值。
        /// </summary>
        /// <param name="helper">当前字符串</param>
        /// <param name="pattern">正则表达式。</param>
        /// <param name="groupname">捕获组的名称（默认为:value）。</param>
        /// <returns>返回捕获组的名称的整型值。</returns>
        public static int GetIntValueByRegex(this string helper, string pattern, string groupname)
        {
            int result = 0;
            string value = helper.GetStringValueByRegex(pattern, groupname);
            if (!string.IsNullOrWhiteSpace(value))
                int.TryParse(value, out result);
            return result;
        }

        /// <summary>
        /// 获取当前字符串符合正则表达式，且 value 组的名称的整型值。
        /// </summary>
        /// <param name="helper">当前字符串</param>
        /// <param name="pattern">正则表达式。</param>
        /// <returns>返回捕获 value 组的名称的整型值。</returns>
        public static int GetIntValueByRegex(this string helper, string pattern)
        {
            return helper.GetIntValueByRegex(pattern, string.Empty);
        }

        /// <summary>
        /// 移出 HTML 字符串两端面的空格。
        /// </summary>
        /// <param name="helper">当前HTML 字符串。</param>
        /// <returns>返回移出空格后的字符串。</returns>
        public static string HtmlTrim(this string helper)
        {
            string result = helper;
            Match m = Regex.Match(result, patternSpace, RegexOptions.IgnoreCase);
            while (m.Success)
            {
                result = Regex.Replace(result, patternSpace, string.Empty);
                m = Regex.Match(result, patternSpace, RegexOptions.IgnoreCase);
            }
            return result;
        }

        /// <summary>
        /// 清理无效的 HTML 属性
        /// </summary>
        /// <param name="helper">当前HTML 字符串。</param>
        /// <returns>返回清理后的 HTML 字符串。</returns>
        public static string ClaerHtmlAttribute(this string helper)
        {
            if (!string.IsNullOrWhiteSpace(helper) && Regex.IsMatch(helper, patternClearHtmlAttribute))
            {
                helper = Regex.Replace(helper, patternClearHtmlAttribute, new MatchEvaluator(m =>
                {
                    return m.Value.Replace(m.Groups["clear"].Value, string.Empty);
                }));
            }
            return helper;
        }

        /// <summary>
        /// 转为全角的函数(SBC case)
        /// </summary>
        /// <param name="helper">要转换的字符串。</param>
        /// <returns>返回转换结果字符串。</returns>
        public static string ToSBC(this string helper)
        {
            return helper.ToDBC(string.Empty);
        }

        /// <summary>
        /// 转为全角的函数(SBC case)
        /// </summary>
        /// <param name="helper">要转换的字符串。</param>
        /// <param name="special">是需要转换的字符所串成的字符串（为空时，不做限制，转换所有字符）。</param>
        /// <returns>返回转换结果字符串。</returns>
        public static string ToSBC(this string helper, string special)
        {
            if (string.IsNullOrWhiteSpace(helper)) return string.Empty;
            //半角转全角：
            char[] c = helper.ToCharArray();
            if (string.IsNullOrWhiteSpace(special))
            {
                for (int i = 0; i < c.Length; i++)
                {
                    if (c[i] == 32)
                    {
                        c[i] = (char)12288;
                        continue;
                    }
                    if (c[i] < 127)
                        c[i] = (char)(c[i] + 65248);
                }
            }
            else
            {
                char[] s = special.ToCharArray();
                for (int i = 0; i < c.Length; i++)
                {
                    if (s.Contains(c[i]))
                    {
                        if (c[i] == 32)
                        {
                            c[i] = (char)12288;
                            continue;
                        }
                        if (c[i] < 127)
                            c[i] = (char)(c[i] + 65248);
                    }
                }
            }
            return new string(c);
        }

        /// <summary>
        ///  转为半角的函数(DBC case)
        /// </summary>
        /// <param name="helper">要转换的字符串。</param>
        /// <returns>返回转换结果字符串。</returns>
        public static string ToDBC(this string helper)
        {
            return helper.ToDBC(string.Empty);
        }

        /// <summary>
        ///  转为半角的函数(DBC case)
        /// </summary>
        /// <param name="helper">要转换的字符串。</param>
        /// <param name="special">是需要转换的字符所串成的字符串（为空时，不做限制，转换所有字符）。</param>
        /// <returns>返回转换结果字符串。</returns>
        public static string ToDBC(this string helper, string special)
        {
            if (string.IsNullOrWhiteSpace(helper)) return string.Empty;
            char[] c = helper.ToCharArray();
            if (string.IsNullOrWhiteSpace(special))
            {
                for (int i = 0; i < c.Length; i++)
                {
                    if (c[i] == 12288)
                    {
                        c[i] = (char)32;
                        continue;
                    }
                    if (c[i] > 65280 && c[i] < 65375)
                        c[i] = (char)(c[i] - 65248);
                }
            }
            else
            {
                char[] s = special.ToCharArray();
                for (int i = 0; i < c.Length; i++)
                {
                    if (s.Contains(c[i]))
                    {
                        if (c[i] == 12288)
                        {
                            c[i] = (char)32;
                            continue;
                        }
                        if (c[i] > 65280 && c[i] < 65375)
                            c[i] = (char)(c[i] - 65248);
                    }
                }
            }
            return new string(c);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static TResult ToObjectByXml<TResult>(this string helper)
        {
            TResult result = default(TResult);
            if (!string.IsNullOrWhiteSpace(helper))
            {

                XmlSerializer serializer = new XmlSerializer(typeof(TResult), string.Empty);
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(helper)))
                {
                    result = (TResult)serializer.Deserialize(ms);
                }
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static TResult ToEntityByXml<TResult>(this Stream helper)
        {
            TResult result = default(TResult);
            if (helper == null) throw new ArgumentNullException("helper");
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TResult), string.Empty);
                result = (TResult)serializer.Deserialize(helper);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Count"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static string DecimalToNRadix(this string Count, short n)
        {
            return DecimalToNRadix(Convert.ToUInt64(Count), n);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Count"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static string DecimalToNRadix(this ulong Count, short n)
        {
            if (n > 62) return "进制不能大于62";
            string returnValue = "";
            ulong nextValue = Count;
            ulong module = 0, _n = (ulong)n;
            while (nextValue > 0)
            {
                module = nextValue % _n;
                nextValue /= _n;
                returnValue = _word[module].ToString() + returnValue;
            }
            return returnValue.Trim().Length > 0 ? returnValue.Trim() : "0";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Count"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static ulong DesRadixToDecimal(this string Count, short n)
        {
            Hashtable htCount = new Hashtable();
            for (int i = 0; i < _word.Length; i++)
            {
                htCount.Add(_word[i].ToString(), i.ToString());
            }
            char[] stringChar = Count.ToCharArray();
            ulong returnValue = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                int pos = stringChar.Length - i - 1;
                returnValue += Convert.ToUInt64(Convert.ToUInt64(htCount[stringChar[i].ToString()]) * Math.Pow(Convert.ToUInt64(n), Convert.ToUInt64(pos)));
            }
            return returnValue;
        }
        
        /// <summary>
        /// 处理手机号敏感数字
        /// </summary>
        /// <param name="_phoneNumber"></param>
        /// <returns></returns>
        public static string GetPhoneNumberDealWith(string _phoneNumber)
        {
            if (string.IsNullOrWhiteSpace(_phoneNumber)) return string.Empty;
            var re = new Regex("(\\d{3})(\\d{4})(\\d{4})", RegexOptions.None);
            return re.Replace(_phoneNumber, "$1****$3");

        }

        /// <summary>
        /// 处理用户敏感的用户名或匿名
        /// </summary>
        /// <param name="_userName"></param>
        /// <returns></returns>
        public static string GetUserNameDealWith(string _userName)
        {
            if (string.IsNullOrWhiteSpace(_userName)) return string.Empty;
            string _userNameVal = string.Empty;
            string valEmail = "^([\\w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$";//邮箱
            string valMobile = "^13[0-9]{9}|15[012356789][0-9]{8}|18[0123456789][0-9]{8}|147[0-9]{8}$";//手机
            string valTel = "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$";//电话号码的函数(包括验证国内区号,国际区号,分机号)
            if (Regex.IsMatch(_userName, valEmail) || Regex.IsMatch(_userName, valMobile) || Regex.IsMatch(_userName, valTel))
                _userNameVal = "*****" + _userName.RightByHtml(12).Remove(0, 5);
            else
                _userNameVal = _userName;
            return _userNameVal;
        }

        public static string GetUserNameDealWiths(string _userName)
        {
            if (string.IsNullOrWhiteSpace(_userName)) return string.Empty;
            string _userNameVal = string.Empty;
            string valEmail = "^([\\w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$";//邮箱
            string valMobile = "^13[0-9]{9}|15[012356789][0-9]{8}|18[0123456789][0-9]{8}|147[0-9]{8}$";//手机
            string valTel = "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$";//电话号码的函数(包括验证国内区号,国际区号,分机号)
            if (Regex.IsMatch(_userName, valEmail) || Regex.IsMatch(_userName, valMobile) || Regex.IsMatch(_userName, valTel))
                _userNameVal = "*****" + _userName.RightByHtml(20).Remove(0, 5);
            else
                _userNameVal = _userName;
            return _userNameVal;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="html"></param>
        /// <param name="attrName"></param>
        /// <param name="attrValue"></param>
        /// <returns></returns>
        public static string GetOutterHtml(this string html, string attrName, string attrValue)
        {
            if (string.IsNullOrWhiteSpace(html)) return string.Empty;
            string result = html;
            Match match = null;
            try
            {
                string pattern = "<(?<HtmlTag>[\\w]+)[^>]*?>((?<Nested><\\k<HtmlTag>[^>]*>)|</\\k<HtmlTag>>(?<-Nested>)|[\\s\\S]*?)*</\\k<HtmlTag>>";
                if (!string.IsNullOrWhiteSpace(attrName))
                    pattern = string.IsNullOrWhiteSpace(attrValue) ? string.Concat("<(?<HtmlTag>", attrName.Trim(), ")[^>]*?>((?<Nested><\\k<HtmlTag>[^>]*>)|</\\k<HtmlTag>>(?<-Nested>)|[\\s\\S]*?)*</\\k<HtmlTag>>") : string.Concat("<(?<HtmlTag>[\\w]+)[^>]*\\s+?", attrName.Trim(), "=(?<Quote>[\"']?)", attrValue.Trim(), "(?(Quote)\\k<Quote>)[^>]*?(/>|>((?<Nested><\\k<HtmlTag>[^>]*>)|</\\k<HtmlTag>>(?<-Nested>)|[\\s\\S]*?)*</\\k<HtmlTag>>)");
                match = Regex.Match(html, pattern, RegexOptions.IgnoreCase);
                if (match.Success) result = match.Value.Trim();
            }
            catch (Exception ex)
            {
                //Logger.LogException(ex);
                throw ex;
            }
            finally
            {
                if (match != null)
                    GC.SuppressFinalize(match);
                match = null;
                GC.Collect();
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="html"></param>
        /// <param name="tagName"></param>
        /// <returns></returns>
        public static string GetOutterHtml(this string html, string tagName)
        {
            return html.GetOutterHtml(tagName, string.Empty);
        }

        /// <summary>
        /// 获取指定长度的纯数字随机数字串
        /// </summary>
        /// <param name="intlong">数字串长度</param>
        /// <returns>纯数字随机数字串</returns>
        public static string GetRandomNum(int intlong)
        {
            StringBuilder w = new StringBuilder(string.Empty);

            for (int i = 0; i < intlong; i++)
            {
                w.Append(rand.Next(10));
            }

            return w.ToString();
        }

        /// <summary>
        /// 将字符串转换成时间间隔
        /// </summary>
        /// <param name="str"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static TimeSpan ToTimeSpan(this string str, TimeSpan? defaultValue = null)
        {
            TimeSpan timeSpan = defaultValue ?? TimeSpan.Zero;
            Match m = Regex.Match(str, "^(?<value>\\d+)(?<type>[dhms]{0,1})$", RegexOptions.IgnoreCase);
            if (m.Success)
            {
                string type = m.Groups["type"].Value;
                type = string.IsNullOrWhiteSpace(type) ? "H" : type.ToUpper().Trim();
                int value = Convert.ToInt32(m.Groups["value"].Value);
                switch (type)
                {
                    case "D":
                        timeSpan = TimeSpan.FromDays(value);
                        break;
                    case "H":
                        timeSpan = TimeSpan.FromHours(value);
                        break;
                    case "M":
                        timeSpan = TimeSpan.FromMinutes(value);
                        break;
                    case "S":
                        timeSpan = TimeSpan.FromSeconds(value);
                        break;
                    default:
                        timeSpan = TimeSpan.FromHours(value);
                        break;
                }
            }
            return timeSpan;
        }
        #region 私有方法

        private static string LeftOfSpecial(this string helper, string pattern, int length, bool hasEllipsis)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                Regex regex = new Regex(pattern, RegexOptions.Compiled);
                char[] stringChar = helper.ToCharArray();
                StringBuilder sb = new StringBuilder();
                int nLength = 0;
                for (int i = 0; i < stringChar.Length; i++)
                {
                    if (regex.IsMatch((stringChar[i]).ToString()))
                    {
                        nLength += 2;
                    }
                    else
                    {
                        nLength = nLength + 1;
                    }

                    if (nLength <= length)
                    {
                        sb.Append(stringChar[i]);
                    }
                    else
                    {
                        if (hasEllipsis) sb.Append("...");
                        break;
                    }
                }
                return sb.ToString();
            }
            return string.Empty;
        }

        private static string RightOfSpecial(this string helper, string pattern, int length, bool hasEllipsis)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                Regex regex = new Regex(pattern, RegexOptions.Compiled);
                char[] stringChar = helper.ToCharArray();
                StringBuilder sb = new StringBuilder();
                int nLength = 0;
                for (int i = stringChar.Length - 1; i > -1; i--)
                {
                    if (regex.IsMatch((stringChar[i]).ToString()))
                        nLength += 2;
                    else
                        nLength = nLength + 1;
                    if (nLength <= length)
                        sb.Append(stringChar[i]);
                    else
                    {
                        if (hasEllipsis) sb.Insert(0, "...");
                        break;
                    }
                }
                return sb.ToString();
            }
            return string.Empty;
        }

        private static string MiddleOfSpecial(this string helper, string pattern, int length)
        {
            if (!string.IsNullOrWhiteSpace(helper))
            {
                helper = helper.Trim();
                Regex regex = new Regex(pattern, RegexOptions.Compiled);
                char[] stringChar = helper.ToCharArray();
                StringBuilder Bsb = new StringBuilder();
                StringBuilder Esb = new StringBuilder();
                string strReturnValue;
                int TnLength = 0, nLength = 0;
                for (int i = 0; i < stringChar.Length; i++)
                {
                    if (regex.IsMatch((stringChar[i]).ToString()))
                        TnLength += 2;
                    else
                        TnLength = TnLength + 1;
                }
                if (TnLength > length)
                {
                    for (int i = 0; i < stringChar.Length; i++)
                    {
                        if (regex.IsMatch((stringChar[i]).ToString()))
                            nLength += 2;
                        else
                            nLength = nLength + 1;
                        if (nLength <= Convert.ToInt32(length / 2))
                            Bsb.Append(stringChar[i]);
                        else if (Convert.ToInt32(TnLength - nLength) <= Convert.ToInt32(length / 2))
                            Esb.Append(stringChar[i]);
                        else
                            continue;
                    }
                    strReturnValue = Bsb.ToString() + "..." + Esb.ToString();
                }
                else
                    strReturnValue = helper;
                return strReturnValue;
            }
            return string.Empty;
        }
        #endregion

        
        /// <summary>
        /// 在 HTML 字符串前面加上顺序号。
        /// </summary>
        /// <param name="html">HTML 字符串。</param>
        /// <param name="serialNumber">顺序号</param>
        /// <param name="score">分数</param>
        /// <returns>返回带顺序号的 HTML 字符串。</returns>
        public static string HtmlSerialNumber(this string html, int serialNumber, decimal score)
        {
            string result = html;
            if ((!string.IsNullOrWhiteSpace(html)) && regexDiv.IsMatch(html.Trim()))
                result = regexDiv.Replace(html.Trim(), new MatchEvaluator(m => string.Concat(m.Value, serialNumber, "．")));
            else
            {
                if (score <= 0) result = string.Concat(serialNumber, "．", html);
                else result = string.Concat(serialNumber, "．", string.Format("({0}分)", score), html);
            }

            return result;
        }
    }
}